package com.xoa.controller.crm;

import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.crm.CrmManagerMapper;
import com.xoa.dao.crm.CustomerMapper;
import com.xoa.dao.crm.LinkmanMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.common.SysCode;
import com.xoa.model.crm.*;
import com.xoa.model.users.Users;
import com.xoa.service.crm.CustomerService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by qiyang on 2019/5/23.
 */
@Controller
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    @Autowired
    private LinkmanMapper linkmanMapper;

    @Autowired
    private SysCodeMapper sysCodeMapper;

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private CrmManagerMapper crmManagerMapper;

    //映射
    @RequestMapping("/salesWorkbench")
    public String myAttendance(HttpServletRequest request) {
        return "/app/crm/customer/salesWorkbench";
    }
    //添加页面
    @RequestMapping("/addWorkbench")
    public String newLandResources() {
        return "app/crm/customer/addWorkbench";
    }
    //修改页面
    @RequestMapping("/updateWorkbench")
    public String updateLandResources() {
        return "app/crm/customer/updateWorkbench";
    }

    //跟进页面
    @RequestMapping("/followWorkbench")
    public String followWorkbenchLandResources() {
        return "app/crm/customer/followWorkbench";
    }

    //导入页面
    @RequestMapping("/insertImport")
    public String followWorkbenchinsertImport() {
        return "app/crm/customer/insertImport";
    }
    //crm设置界面
    @RequestMapping("/Crmsetup")
    public String crmSetIndex() {
        return "app/crm/customer/SetIndex";
    }

    //处理时间  将前台传过来的时间存到数据库中
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }
    @RequestMapping("powerCustomer")
    @ResponseBody
    public ToJson<String> powerCustomer(HttpServletRequest request, CustomerWithBLOBs customerWithBLOBs){
        ToJson json =new ToJson<Integer>(1,"err");
        try {
            String data =customerService.powerCustomer(customerWithBLOBs);

            if(data!=null){
                json.setObject(data);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询客户
     */
    @RequestMapping("/potentialCustomer")
    @ResponseBody
    public ToJson<CustomerWithBLOBs> potentialCustomer1(HttpServletRequest request, Integer page, Integer pageSize, Boolean useFlag, CustomerWithBLOBs customer, String export, HttpServletResponse response){
        Map<String,Object> map= new HashMap<String, Object>();

        //获取登录用户
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);

        customer.setIsDeleted(Byte.valueOf("0"));
        customer.setCreator(users.getUserId());
        map.put("obj",customer);
        ToJson json =new ToJson<CustomerWithBLOBs>(1,"err");
        String createdTimeStr=request.getParameter("createdTimeStr");
        String createdTimeEnd=request.getParameter("createdTimeEnd");
        map.put("createdTimeStr",createdTimeStr);
        map.put("createdTimeEnd",createdTimeEnd);


        try {
            //查看我的客户
            List<CustomerWithBLOBs> data = customerService.potentialmeCustomer(page, pageSize, useFlag, map,export,response);
            //List<CustomerWithBLOBs> customerWithBLOBs = customerMapper.selectByCreator(users.getUserId());
            //判断完后总数
            List<CustomerWithBLOBs> customerWithBLOBs = customerService.CustomerSoles(page, pageSize, map,response);
            if (data != null) {
                PageParams pageParams = (PageParams) map.get("page");
                json.setTotleNum(customerWithBLOBs.size());
                json.setObj(data);
                json.setFlag(0);
                json.setMsg("true");
            }


        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询客户（下属）
     */
    @RequestMapping("/potentialCustomerSole")
    @ResponseBody
    public ToJson<CustomerWithBLOBs> potentialCustomerSole(HttpServletRequest request, Integer page, Integer pageSize, Boolean useFlag, CustomerWithBLOBs customer, String export, HttpServletResponse response){
        Map<String,Object> map= new HashMap<String, Object>();
        customer.setIsDeleted(Byte.valueOf("0"));

        ToJson json =new ToJson<CustomerWithBLOBs>(1,"err");
        String createdTimeStr=request.getParameter("createdTimeStr");
        String createdTimeEnd=request.getParameter("createdTimeEnd");
        map.put("createdTimeStr",createdTimeStr);
        map.put("createdTimeEnd",createdTimeEnd);
        //获取登录用户
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        List<CrmManager> crmManagers = crmManagerMapper.selectByManagerId(users.getUserId());
        HashSet<String> hashSet = new HashSet();
            for (CrmManager manager : crmManagers) {
                if(manager.getSalesId().contains(",")){
                    String[] split = manager.getSalesId().split(",");
//                    String salesId = manager.getSalesId();
                    for(String str :split){
                        hashSet.add(str);
                    }
                }
            }

        map.put("creators",hashSet);
        map.put("obj",customer);
        try {
            //查看我的客户
            List<CustomerWithBLOBs> data = customerService.potentialCustomerSole(page, pageSize, useFlag, map,export,response);
            //查看我的客户总数
            List<CustomerWithBLOBs> datas = customerService.CustomerSoles(page, pageSize, map,response);
            if (data != null) {
                PageParams pageParams = (PageParams) map.get("page");
                json.setTotleNum(datas.size());
                json.setObj(data);
                json.setFlag(0);
                json.setMsg("true");
            }


        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 添加客户
     * @param request
     * @param customerWithBLOBs
     * @return
     */
    @RequestMapping("insertCustomer")
    @ResponseBody
    public ToJson<Integer> insertCustomer(HttpServletRequest request, CustomerWithBLOBs customerWithBLOBs,Linkman linkman){
        ToJson json =new ToJson<Integer>(1,"err");
        try {
            Integer data =customerService.insert(customerWithBLOBs);
            Integer customerId = customerWithBLOBs.getCustomerId();
            linkman.setCustomerId(customerId);
            linkmanMapper.insertSelective(linkman);
           /* Integer customerId = customerWithBLOBs.getCustomerId();
            linkman.setCustomerId(customerId);
            int data1 = customerService.insertLinkMan(linkman);*/
            if(data!=null){
                json.setObject(data);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 删除客户
     * @param request
     * @param customerId
     * @return
     */
    @RequestMapping("deleteCustomer")
    @ResponseBody
    public ToJson<Integer> deleteByPrimaryKey(HttpServletRequest request, Integer customerId){
        ToJson json =new ToJson<Integer>(1,"err");
        try {
            Integer data =customerService.deleteByPrimaryKey(customerId);
            if(data!=null){
                json.setObject(data);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 编辑回显
     * @param request
     * @param customerId
     * @return
     */
    @RequestMapping("/selectCustomerById")
    @ResponseBody
    public ToJson<CustomerWithBLOBs> selectByPrimaryKey(HttpServletRequest request, Integer customerId){
        ToJson json =new ToJson<CustomerWithBLOBs>(1,"err");
        try {
            CustomerWithBLOBs data =customerService.selectByPrimaryKey(customerId);
            //获取创建人
            String creator = data.getCreator();
            //获取用户对象
            Users users = usersMapper.getByUserId(creator);
            //处理头像问题
            String realPath = request.getSession().getServletContext().getRealPath("/");//获取项目路径

            if(!StringUtils.checkNull(users.getAvatar())){
                if(!"0".equals(users.getAvatar())&&!"1".equals(users.getAvatar())){
                    String avatarPath=realPath+"ui"+System.getProperty("file.separator")
                            +"img"+System.getProperty("file.separator")+"user"+System.getProperty("file.separator")
                            +users.getAvatar();
                    File file=new File(avatarPath);
                    if(!file.exists()){
                        if(!StringUtils.checkNull(users.getSex())){
                            users.setAvatar(users.getSex());
                        }else{
                            users.setAvatar("0");
                        }
                    }
                }

                data.setAvatar(users.getAvatar());
            }else{
                if(!StringUtils.checkNull(users.getSex())){
                    users.setAvatar(users.getSex());
                }else{
                    users.setAvatar("0");
                }
                data.setAvatar(users.getAvatar());
            }
            data.setCreator(users.getUserName());


            if(data!=null){
                json.setObject(data);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 编辑客户
     */
    @RequestMapping("updateByPrimaryKeyWithBLOBs")
    @ResponseBody
    public ToJson<Integer> updateByPrimaryKeyWithBLOBs(HttpServletRequest request, CustomerWithBLOBs record){
        ToJson json =new ToJson<Integer>(1,"err");
        try {
            Integer data =customerService.updateByPrimaryKeyWithBLOBs(record);
            if(data!=null){
                json.setObject(data);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询客户状态
     */
    @RequestMapping("selectByStatus")
    @ResponseBody
    public ToJson<Integer> selectByStatus(HttpServletRequest request){
        ToJson json =new ToJson<Integer>(1,"err");
        try {
            List<SysCode> data=sysCodeMapper.getSysCode("CUSTOMER_STATUS");
            if(data!=null){
                json.setObject(data);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询客户级别
     */
    @RequestMapping("selectByLevel")
    @ResponseBody
    public ToJson<Integer> selectByLevel(HttpServletRequest request){
        ToJson json =new ToJson<Integer>(1,"err");
        try {
            List<SysCode> data=sysCodeMapper.getSysCode("CUSTOMERLEVEL");
            if(data!=null){
                json.setObject(data);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询客户来源
     */
    @RequestMapping("selectBySource")
    @ResponseBody
    public ToJson<Integer> selectBySource(HttpServletRequest request){
        ToJson json =new ToJson<Integer>(1,"err");
        try {
            // List<CustomerWithBLOBs> data = customerService.selectBySource();
            List<SysCode> sysCodes=sysCodeMapper.getSysCode("CUSTOMERSOURCE");
            if(sysCodes!=null){
                json.setObj(sysCodes);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 添加跟进
     */
    @RequestMapping("insertFollow")
    @ResponseBody
    public ToJson<Integer> insertFollow(HttpServletRequest request, Follow follow){
        ToJson json =new ToJson<Integer>(1,"err");
        try {
            Integer data = customerService.insertFollow(follow);
            if(data!=null){
                json.setObject(data);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 删除跟进
     */
    @RequestMapping("deleteFollow")
    @ResponseBody
    public ToJson<Integer> deleteFollow(HttpServletRequest request, Integer followId){
        ToJson json =new ToJson<Integer>(1,"err");
        try {
            Integer data = customerService.deleteFollow(followId);
            if(data!=null){
                json.setObject(data);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询跟进
     */
    @RequestMapping("findAllFollow")
    @ResponseBody
    public ToJson<Follow> findAllFollow(HttpServletRequest request, Integer customerId, Integer page, Integer pageSize, boolean useFlag){
        ToJson json =new ToJson<Product>(1,"err");
        Map<String, Object> map = new HashMap<String, Object>();
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        map.put("page", pageParams);
        map.put("customerId",customerId);
        try {
            List<Follow> data = customerService.findAllFollow(map);
            for (Follow follow: data) {
                //获取创建人
                String creator = follow.getCreator();
                //获取用户对象
                Users users = usersMapper.getByUserId(creator);
                //处理头像问题
                String realPath = request.getSession().getServletContext().getRealPath("/");//获取项目路径

                if(!StringUtils.checkNull(users.getAvatar())){
                    if(!"0".equals(users.getAvatar())&&!"1".equals(users.getAvatar())){
                        String avatarPath=realPath+"ui"+System.getProperty("file.separator")
                                +"img"+System.getProperty("file.separator")+"user"+System.getProperty("file.separator")
                                +users.getAvatar();
                        File file=new File(avatarPath);
                        if(!file.exists()){
                            if(!StringUtils.checkNull(users.getSex())){
                                users.setAvatar(users.getSex());
                            }else{
                                users.setAvatar("0");
                            }
                        }
                    }
                    follow.setAvatar(users.getAvatar());
                }else{
                    if(!StringUtils.checkNull(users.getSex())){
                        users.setAvatar(users.getSex());
                    }else{
                        users.setAvatar("0");
                    }
                    follow.setAvatar(users.getAvatar());
                }
                follow.setCreator(users.getUserName());
            }
            if(data!=null){
                json.setTotleNum(pageParams.getTotal());
                json.setObj(data);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }
    /**
     * 查询跟进方式
     */
    @RequestMapping("selectByType")
    @ResponseBody
    public ToJson<Integer> selectByType(HttpServletRequest request){
        ToJson json =new ToJson<Integer>(1,"err");
        try {
            // List<CustomerWithBLOBs> data = customerService.selectBySource();
            List<SysCode> sysCodes=sysCodeMapper.getSysCode("FOLLOWUPMODE");
            if(sysCodes!=null){
                json.setObj(sysCodes);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询客户行业
     */
    @RequestMapping("selectByIndustry")
    @ResponseBody
    public ToJson<Integer> selectByIndustry(HttpServletRequest request){
        ToJson json =new ToJson<Integer>(1,"err");
        try {
            // List<CustomerWithBLOBs> data = customerService.selectBySource();
            List<SysCode> sysCodes=sysCodeMapper.getSysCode("CUSTOMERINDUSTRY");
            if(sysCodes!=null){
                json.setObj(sysCodes);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 方法介绍:   查询和导出接口
     * 参数说明:   @param  user,sortType,isExport
     * 参数说明:
     *
     * @return ToJson 返回用户信息
     */
    @ResponseBody
    @RequestMapping(value = "/customerExport", produces = {"application/json;charset=UTF-8"})
    public ToJson<CustomerWithBLOBs> queryExportUsers(HttpServletRequest request, HttpServletResponse response) {
        return customerService.customerExport(request,response);
    }

    @ResponseBody
    @RequestMapping(value = "/insertImport", produces = {"application/json;charset=UTF-8"})
    public ToJson<CustomerWithBLOBs> insertImport(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        return customerService.insertImport(request,response,file);
    }

}
